package com.yuanxiao.common.api.aspect;

import cn.hutool.json.JSONUtil;
import com.yuanxiao.common.api.entity.SysLogEntity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.yuanxiao.common.api.annotation.SysLog;
import com.yuanxiao.common.api.entity.dto.SysUserAuthDTO;
import com.yuanxiao.common.api.service.AsyncSaveLogExecutorService;
import com.yuanxiao.common.core.constant.GlobalConstants;
import com.yuanxiao.common.web.util.HttpContextUtils;
import com.yuanxiao.common.web.util.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 系统日志，切面处理类
 */
@Aspect
@Component
public class SysLogAspect {

	@Autowired
	private AsyncSaveLogExecutorService asyncSaveLogExecutorService;

	@Pointcut("@annotation(com.yuanxiao.common.api.annotation.SysLog)")
	public void logPointCut() { 
		
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		// System.out.println("#### 1 ####");
		long beginTime = System.currentTimeMillis();
		//执行方法
		Object result = point.proceed();
		//执行时长(毫秒)
		long time = System.currentTimeMillis() - beginTime;

		// System.out.println("####2####");
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method method = signature.getMethod();

		SysLogEntity sysLog = new SysLogEntity();
		SysLog syslog = method.getAnnotation(SysLog.class);
		if(syslog != null){
			//注解上的描述
			sysLog.setOperation(syslog.value());
		}

		//请求的方法名
		String className = point.getTarget().getClass().getName();
		String methodName = signature.getName();
		sysLog.setMethod(className + "." + methodName + "()");

		//请求的参数
		Object[] args = point.getArgs();
		try{
			String params = JSONUtil.toJsonStr (args);
			sysLog.setParams(params);
		}catch (Exception e){

		}

		//获取request
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		//设置IP地址
		//sysLog.setIp(NetworkUtil.getIpAddr(request));
		sysLog.setIp (request.getHeader (GlobalConstants.REQUEST_HEADER_KEY_CLIENT_REAL_IP));

		SysUserAuthDTO userEntity = JSONUtil.toBean (JwtUtils.getUserInfoJSON (), SysUserAuthDTO.class);
		sysLog.setUserId (userEntity.getId ());
		sysLog.setUsername(userEntity.getUsername());
		sysLog.setDeptId (userEntity.getDeptId ());
		sysLog.setDeptIds (userEntity.getDeptIds ());
		sysLog.setTime(time);
		//保存日志
		asyncSaveLogExecutorService.saveLog (sysLog);

		// System.out.println("#### 3 ####" + DateUtil.now ());

		return result;
	}
}
